package com.clusterswisdom.horn.api.event;

import com.alibaba.fastjson.JSON;
import com.clusterswisdom.horn.api.db.DbUtil;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.ioc.api.HornConfig;
import com.clusterswisdom.horn.api.ioc.event.HornEvent;

public class EventProcessor extends BaseProcessor implements Runnable {

	private HornEvent event;
	
	public EventProcessor(HornEvent event) {
		this.event = event;
	}
	
	@Override
	public void run() {
		ApiConfig apiConfig = HornConfig.getConfig().getApiConfig(event.getChanel(), event.getService(), event.getMethod());
		if (apiConfig == null) {
			return;
		}
		
		Long logId = null;
		try {
			if (apiConfig.isLog()) {
				logId = saveEventLog(event);
			}
			
			HornResponse response = super.process(apiConfig, event.getParam());
			String pushReson = super.pushData(apiConfig, response);
			if (logId != null) {
				DbUtil.getUtil().logResult(logId, apiConfig.getResponse().getType().getValue(), pushReson);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			DbUtil.getUtil().rollback();
			sendException(apiConfig, logId, e);
			
		} finally {
			DbUtil.getUtil().close();
			
		}
	}
	
	private Long saveEventLog(HornEvent event) {
		String paramValue = JSON.toJSONString(event.getParam());
		String url = event.getService() + "." + event.getMethod();
		return DbUtil.getUtil().saveLog(event.getChanel(), "event", url, paramValue);
	}
}
